package com.java110.mall.openapi.bmo.impl;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.dto.integral.IntegralWithdrawalDto;
import com.java110.intf.acct.IIntegralWithdrawalV1InnerServiceSMO;
import com.java110.mall.openapi.bmo.IMallCommonApiBmo;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("queryCommunityIntegralApplyBmoImpl")
public class QueryCommunityIntegralApplyBmoImpl implements IMallCommonApiBmo {

    @Autowired
    private IIntegralWithdrawalV1InnerServiceSMO integralWithdrawalV1InnerServiceSMOImpl;

    @Override
    public void validate(ICmdDataFlowContext context, JSONObject reqJson) {

        Assert.jsonObjectHaveKey(reqJson, "page", "请求中未包含page信息");
        Assert.jsonObjectHaveKey(reqJson, "row", "请求中未包含row信息");
        Assert.hasKeyAndValue(reqJson, "integralId", "未包含积分");
        Assert.hasKeyAndValue(reqJson, "communityId", "未包含小区");
    }

    @Override
    public void doCmd(ICmdDataFlowContext context, JSONObject reqJson) {
        IntegralWithdrawalDto integralWithdrawalDto = BeanConvertUtil.covertBean(reqJson, IntegralWithdrawalDto.class);
        integralWithdrawalDto.setShopId(reqJson.getString("communityId"));

        int count = integralWithdrawalV1InnerServiceSMOImpl.queryIntegralWithdrawalsCount(integralWithdrawalDto);

        List<IntegralWithdrawalDto> integralWithdrawalDtos = null;

        if (count > 0) {
            integralWithdrawalDtos = integralWithdrawalV1InnerServiceSMOImpl.queryIntegralWithdrawals(integralWithdrawalDto);
        } else {
            integralWithdrawalDtos = new ArrayList<>();
        }

        ResultVo resultVo = new ResultVo((int) Math.ceil((double) count / (double) reqJson.getInteger("row")), count, integralWithdrawalDtos);

        ResponseEntity<String> responseEntity = new ResponseEntity<String>(resultVo.toString(), HttpStatus.OK);

        context.setResponseEntity(responseEntity);
    }
}
